package logic

import (
	"changes/changesrpc/changesrpc"
	"changes/changesrpc/internal/svc"
	"changes/model/mysql"
	"changes/model/redisinit"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *changesrpc.ListRequest) (*changesrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var change []mysql.Change

	get := redisinit.Client.Get("list")

	if get.Val() == "" {
		mysql.DB.Find(&change)
		marshal, _ := json.Marshal(&change)
		redisinit.Client.Set("list", marshal, time.Minute*30)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &change)
		fmt.Println("redis")
	}

	var lists []*changesrpc.ShowList

	for _, i := range change {
		list := changesrpc.ShowList{
			Id:     int64(i.ID),
			Title:  i.Title,
			Num:    int64(i.Num),
			Status: i.Status,
			Timed:  i.Timed,
		}
		lists = append(lists, &list)
	}

	return &changesrpc.ListResponse{
		List: lists,
	}, nil
}
